package com.equinox.consul.zuul.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import lombok.extern.slf4j.Slf4j;

/**
 * zuul过滤器
 * 
 * @author Thinker
 *
 */
@Component
@Slf4j
public class MyFilter extends ZuulFilter{
	/**
	 *  表示是否需要执行该filter，true表示执行，false表示不执行
	 */
	@Override
	public boolean shouldFilter() {
		
		return true;
	}
	/**
	 *  操作
	 */
	@Override
	public Object run() throws ZuulException {
		RequestContext ctx=RequestContext.getCurrentContext();
		HttpServletRequest request=ctx.getRequest();
		String token=request.getParameter("token");
		log.info(token);
		if(token==null) {
			log.warn("there is no request token");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			try {
				ctx.getResponse().getWriter().write("there is no request token");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		log.info("ok");
		return null;
	}
	/**
	 * //定义filter类型，有pre,route,post,error 四种
	 * pre:
	 *     -3:标记处理Servlet的类型
	 *     -2:包装HttpServletRequest请求
	 *     -1: 包装请求体
	 * route:
	 *     1: 	标记调试标志
	 *     5: 处理请求上下文供后续使用
	 *     10:  	serviceId请求转发
	 *     100: url请求转发
	 *     500:  	forward请求转发
	 * post:
	 *     0: 处理有错误的请求响应
	 *     1000:处理正常的请求响应
	 */
	@Override
	public String filterType() {
		
		return "pre";  
	}
	/**
	 * 定义filter的顺序，数字越小表示顺序越高，越先放行
	 */
	@Override
	public int filterOrder() {
		
		return 0;
	}

}
